<?php
namespace Admin\Model;

use Think\Model;

class EmployeeModel extends Model{
	const STATE_BAN = 0; /*禁止登陆*/
	// const STATE_PROBATION = 1; /*试用期*/
	const STATE_OK = 2; /*正式员工*/
	const STATE_LEAVE = -1; /*离职员工*/
	//后台员工登陆字段
	// const USER_LOGIN_FIELD = 'user_id,login_name,nickname,sector_id,role_id,phone,qq,email,weixin,state,is_deleted,last_time,last_ip,sex';
	protected $tableName = 'user_extension';
	/**
	 * 获取下属部门员工信息
	 * @param  int     $sector_id     部门ID
	 * @param  boolean $include_me    是否包括自己的部门
	 * @param  boolean $include_leave 是否包括离职员工
	 * @return [type]                 [description]
	 */
	public function subsector_user( $sector_id = false, $include_me = true,$include_leave = false )
	{
		$wheres = array();
		if( $sector_id ){
			$uinfo = self::loadFromSession();
			if( !$uinfo ) return false;
			$sector_id = $uinfo['sector_id'];
		}
		$MSector = D('Sector');
		$secs = $MSector->sub_sector( $sector_id, $include_me);
		$wheres['_string'] = '1=1';
		$wheres['sector_id'] = array('in', $secs );
		if( !$include_leave )
			$wheres['state'] = array('neq', self::STATE_LEAVE );

		$ulist = $this->field("user_id,login_name,nickname,sector_id,role_id")->where( $wheres )->select();
		return $ulist;
	}

	/**
	 * 获取下属岗位员工信息
	 * @param  int     $role_id       岗位ID
	 * @param  boolean $include_me    是否包括自己的岗位
	 * @param  boolean $include_leave 是否包括离职员工
	 * @return [type]                 [description]
	 */
	public function subrole_user( $role_id = false, $include_me = true, $include_leave = false )
	{
		$wheres = array();
		if( !$role_id ){
			$uinfo = self::loadFromSession();
			if( !$uinfo ) return false;
			$role_id = $uinfo['role_id'];
		}
		$MRole = D('Role');
		$roles = $MRole->sub_role( $role_id, $include_me);
		$wheres['_string'] = '1=1';
		$wheres['role_id'] = array('in', $roles );
		if( !$include_leave )
			$wheres['state'] = array('neq', self::STATE_LEAVE );

		$ulist = $this->field("user_id,login_name,nickname,sector_id,role_id")->where( $wheres )->select();
		return $ulist;
	}

	/**
	 *  后台员工登录接口
	 * @param string $uname   用户登录名
	 * @param string $psw     密码
	 * @param string $caption 验证码
	 * @return array  登录结果
	 */
	public function Login( $uname, $psw, $caption = null)
	{
		$logres = array('r'=>0,'d'=>null,'m'=>'');
		$wheres = array();
		if (!$uname || !$psw) {
			$logres['m'] = "提交参数不完整";
		}
		else {
			$uinfo = null;
			$wheres['login_name'] = array('eq', $uname);
			$uinfo = $this->where( $wheres )->find();
			if ($uinfo) {
				$pass = md6($psw.$uname.$uinfo['create_time']);
				if ($pass == $uinfo['pass']) {
					if( $uinfo['state'] == self::STATE_BAN || $uinfo['state'] == self::STATE_LEAVE){
						$logres['m'] = '客户已经禁止登陆';
					}
					else {
						$logres['r'] = 1;
						unset( $uinfo['pass'] );
						$logres['d'] = $this->field(self::USER_LOGIN_FIELD )->where( $wheres )->find();
						$logres['m'] = 'OK';
						/*更新客户登陆信息*/
						$dup = array();
						$dup['last_time'] = date('Y-m-d H:i:s');
						$dup['last_ip'] = get_client_ip();
						$this->where( $wheres )->save( $dup );

						/*获取用户分机配置*/
						$Mphone = M('OmSubphone');
						$whereom = array();
						$whereom['admin_no'] = array('eq', $logres['d']['user_id']);
						$ext = $Mphone->field("om_subphone.subphone,om_subphone.admin_no as uid,om_subphone.line_id,oms.omid,oms.ipaddr")
									  ->join("LEFT JOIN om_server oms on oms.omid=om_subphone.omid")
									  ->where( $whereom )
									  ->find();
						if( $ext )
							$logres['d']['ext'] = $ext;
					}
				}
				else
					$logres['m'] = '密码错误';
			}
			else
				$logres['m'] = '用户不存在';
		}

		return $logres;
	}

	/**
	 * 员工更新自己人信息
	 * @param  int 		$uid   			要更新的员工
	 * @param  array 	$updateInfos 	要更新的客户信息
	 * @param  string   $psw            当前用户密码
	 * @param  string   $newPsw			新密码，为空的时候不更细
	 * @return array    更新后的客户信息
	 */
	public function updateUser($uid, $updateInfos, $psw, $newPsw = false )
	{
		$r = array('r'=>0,'d'=>null,'i'=>'');
		$r['i'] = L('SERVER_BUSY');
		$uinfo = self::loadFromSession();
		if( !$uinfo ){
			$r['i'] = "请登陆后进行操作";
		}
		else{
			if( $uinfo['user_id'] == $uid ){
				//验证密码
				$wheres = array();
				$wheres['user_id'] = array('eq', $uinfo['user_id']);
				$uload = $this->where( $wheres )->find();
				$pass = md6($psw.$uload['login_name'].$uload['create_time']);
				if( $pass == $uload['pass'] ){
					$ups = array();
					$ups['nickname'] = trim( $updateInfos['nickname'] );
					$go = true;
					//更新手机号码
					$wheres['user_id'] = array('neq', $uinfo['user_id']);
					if( $updateInfos['phone']){
						$wheres['phone'] = array('eq', $updateInfos['phone']);
						if( $this->where( $wheres )->find()  ){
							$r['i'] = "该电话号码员工已经使用";
							$go = false;
						}
						else
							$ups['phone'] = $updateInfos['phone'];
						unset( $wheres['phone'] );
					}
					else
						$ups['phone'] = null;
					//更新邮箱
					if( $go && $updateInfos['email']){
						$wheres['email'] = array('eq', $updateInfos['email']);
						if( $this->where( $wheres )->find() ){
							$go = false;
							$r['i'] = "该邮箱已经被别人使用";
						}
						else
							$ups['email'] = $updateInfos['email'];
						unset( $wheres['email'] );
					}
					else
						$upds['email'] = null;
					//更新QQ
					if( $go && $updateInfos['qq'] ){
						$wheres['qq'] = array('eq', $updateInfos['qq']);
						if( $this->where( $wheres )->find() ){
							$go = false;
							$r['i'] = "该QQ号码已经被别人很使用";
						}
						else
							$ups['qq'] =  $updateInfos['qq'];
						unset( $wheres['qq']);
					}
					else
						$ups['qq'] = null;
					//更新微信ID
					if( $go && $updateInfos['weixin'] ){
						$wheres['weixin'] = array('eq', $updateInfos['weixin']);
						if( $this->where( $wheres )->find() ){
							$go = false;
							$r['i'] = '该微信ID已经被别人使用';
						}
						else
							$ups['weixin'] = $updateInfos['weixin'];
						unset( $wheres['weixin'] );
					}
					else
						$ups['weixin'] = null;
					if( $go ){
						$wheres['user_id'] = array('eq', $uload['user_id'] );
						//判断是否更新密码
						if( $newPsw ){
							$ups['pass'] = md6($newPsw.$uload['login_name'].$uload['create_time']);
						}
						$count = $this->where( $wheres )->save( $ups );
						$r['r'] = $count ? ( $newPsw ? 2:1) : 0;
						if( $r['r'] ){
							$r['d'] = $this->field( self::USER_LOGIN_FIELD )->where( $wheres )->find();
						}
					}
				}
				else
					$r['i'] = "当前账号密码验证失败";
			}
			else
				$r['i'] = "更新账号资料与当前登陆账号不一致";
		}
		return $r;
	}

	//从session中加载用户信息　
	public static function loadFromSession( $force = false )
	{
		$uinfo = isset($_SESSION[C('ADMIN_HASH_NAME')]) ? $_SESSION[C('ADMIN_HASH_NAME')] : '';
		if( count( $uinfo ) ){
			$uinfos = authcode( $uinfo , "DECODE");
			$arruinfo = unserialize( $uinfos );
			if( $arruinfo && isset( $arruinfo['user_id'])  ){
				return $arruinfo;
			}
		}
		else
			return false;
	}

	//根据user_id查询user
	public function getUserById($uid){
		$wheres = array();
		$wheres['user_id'] = array('eq',$uid);
		$userInfo = M('User')->where($wheres)
			->field("user.*,role.*,sector.*")
			->join("LEFT JOIN role on role.role_id = user.role_id")
			->join("LEFT JOIN sector on sector.sector_id = user.sector_id")
			->select();
		return $userInfo[0];
	}
	//根据user_id查询user_extension
	public function getUserExtById($uid){
		$wheres = array();
		$wheres['user_id'] = array('eq',$uid);
		$extInfo = M('user_extension')->where($wheres)->find();
		return $extInfo;
	}
	//根据user_id查询嘉奖表hr_commend
	public function getHrCommById($uid){
		$wheres = array();
		$wheres['user_id'] = array('eq',$uid);
		$hrCommInfo = M('hr_commend')->where($wheres)->select();
		return $hrCommInfo;
	}
	//根据user_id查询教育经历hr_education
	public function getHrEduById($uid){
		$wheres = array();
		$wheres['user_id'] = array('eq',$uid);
		$hrEduInfo = M('hr_education')->where($wheres)->select();
		return $hrEduInfo;
	}
	//根据user_id查询家庭成员hr_family
	public function getHrFamById($uid){
		$wheres = array();
		$wheres['user_id'] = array('eq',$uid);
		$hrFamInfo = M('hr_family')->where($wheres)->select();
		return $hrFamInfo;
	}
	//根据user_id查询特殊贡献hr_offer
	public function getHrOffById($uid){
		$wheres = array();
		$wheres['user_id'] = array('eq',$uid);
		$hrOffInfo = M('hr_offer')->where($wheres)->select();
		return $hrOffInfo;
	}
	//根据user_id查询岗位异动hr_postexch
	public function getHrPosById($uid){
		$wheres = array();
		$wheres['user_id'] = array('eq',$uid);
		$hrPosInfo = M('hr_postexch')->where($wheres)
			->field("hr_postexch.*,sold.sector_name as old_sname,snew.sector_name as new_sname,sold.sector_id as old_seId,snew.sector_id as new_seId,rnew.role_name as new_rname,
				rold.role_name as old_rname,rold.role_id as old_roId,rnew.role_id as new_roId")
			->order("hr_postexch.ps_date")
			->join("LEFT JOIN sector sold ON sold.sector_id = hr_postexch.ps_old_sector")
			->join("LEFT JOIN sector snew ON snew.sector_id = hr_postexch.ps_old_sector")
			->join("LEFT JOIN role rold ON rold.role_id = hr_postexch.ps_old_role")
			->join("LEFT JOIN role rnew ON rnew.role_id = hr_postexch.ps_new_role")
			->select();
		return $hrPosInfo;
	}
	//根据user_id查询培训经历hr_train
	public function getHrTraById($uid){
		$wheres = array();
		$wheres['user_id'] = array('eq',$uid);
		$hrTraInfo = M('hr_train')->where($wheres)->select();
		return $hrTraInfo;
	}
	//根据user_id查询入司培训hr_train_com
	public function getHrTraComById($uid){
		$wheres = array();
		$wheres['user_id'] = array('eq',$uid);
		$hrTraComInfo = M('hr_train_com')->where($wheres)->select();
		return $hrTraComInfo;
	}
	//根据user_id查询工作经历hr_workexp
	public function getGongzuoById($uid){
		$wheres = array();
		$wheres['user_id'] = array('eq',$uid);
		$hrGongzuo = M('hr_workexp')->where($wheres)->select();
		return $hrGongzuo;
	}
	//根据user_id查询惩罚记录
	/*public function getChufaById($uid){
		$wheres = array();
		$wheres['user_id'] = array('eq',$uid);
		$hrChufa = M('hr_punish')->where($wheres)->select();
		return $hrChufa;
	}*/
	public function getChufaById($uid){
		$wheres = array();
		$wheres['user_id'] = array('eq',$uid);
		$hrChufa = M("fine_user")->field("p.pub_time,p.description,fine_user.fine_remark,fine_user.fine_type")
								->where($wheres)
								->join("LEFT JOIN user as us on us.user_id = fine_user.sales_id")
								->join("LEFT JOIN fine as p on p.fine_id  = fine_user.fine_id")
								->select();
		return $hrChufa;
	}
	//根据user_id查询离职记录表dimission
	public function getDimisById($uid){
		$wheres = array();
		$wheres['user_id'] = array('eq',$uid);
		$dimis = M('dimission')->where($wheres)->order('dim_addtime desc')->limit(1)->select();
		return $dimis;
	}

	//更改家庭成员hr_family
	public function editFamily($uid,$d){
		$wheres = array();
		$wheres['user_id'] = array('eq',$uid);
		$fam = M('hr_family');
		$delFam = $fam->where( $wheres )->delete();
		$FamRes = false;
		if(count($d) == 0){
			$FamRes = count($d);
		}
		foreach ($d as $value) {
			$value['user_id']  = $uid;
			$FamRes = $fam->add($value);
			if(!$FamRes){
				break;
			}
		}
		return $FamRes;

	}
	//更改教育经历表hr_education
	public function editEdu($uid,$d){
		$wheres = array();
		$wheres['user_id'] = array('eq',$uid);
		$delEdu= M('hr_education')->where( $wheres )->delete();
		$eduRes = false;
		if(count($d) == 0){
			$eduRes = count($d);
		}
		foreach ($d as $value) {
			$value['user_id'] = $uid;
			$eduRes = M('hr_education')->add($value);
			if(!$eduRes){
				break;
			}
		}
		return $eduRes;
	}
	//更改培训经历hr_train
	public function editTrain($uid,$d){
		$wheres = array();
		$wheres['user_id'] = array('eq',$uid);
		$delTrain = M('hr_train')->where( $wheres )->delete();
		$trainRes = false;
		if(count($d) == 0){
			$trainRes = count($d);
		}
		foreach ($d as $value) {
			$value['user_id'] = $uid;
			$trainRes = M('hr_train')->add($value);
			if(!$trainRes){
				break;
			}
		}
		return $trainRes;
	}
	//更改入司培训经历hr_train_com
	public function editTrainCom($uid,$d){
		$wheres = array();
		$wheres['user_id'] = array('eq',$uid);
		$delTrainCom = M('hr_train_com')->where( $wheres )->delete();
		$trainComRes = false;
		if(count($d) == 0){
			$trainComRes = count($d);
		}
		foreach ($d as $value) {
			$value['user_id'] = $uid;
			$trainComRes = M('hr_train_com')->add($value);
			if(!$trainComRes){
				break;
			}
		}
		return $trainComRes;
	}
	//更改工作经历表hr_workexp
	public function editWorkExp($uid,$d){
		$wheres = array();
		$wheres['user_id'] = array('eq',$uid);
		$delWorkExp = M('hr_workexp')->where( $wheres )->delete();
		$workRes = false;
		if(count($d) == 0){
			$workRes = count($d);
		}
		foreach ($d as $value) {
			$value['user_id'] = $uid;
			$workRes = M('hr_workexp')->add($value);
			if(!$workRes){
				break;
			}
		}
		return $workRes;
	}
	//更改岗位异动hr_postexch
	public function editPostExch($uid,$d){
		$wheres = array();
		$wheres['user_id'] = array('eq',$uid);
		$delPostExch = M('hr_postexch')->where( $wheres )->delete();
		$postExchRes = false;
		if(count($d) == 0){
			$postExchRes = count($d);
		}
		$data['sector_id'] = '';
		$data['role_id'] = '';
		foreach ($d as $value) {
			$value['user_id'] = $uid;
			$postExchRes = M('hr_postexch')->add($value);
			$data['sector_id'] = $value['ps_new_sector'];
			$data['role_id'] = $value['ps_new_role'];
			if(!$postExchRes){
				break;
			}
		}
		if($postExchRes){
			M('user')->where('user_id='.$uid)->save($data);
		}
		return $postExchRes;
	}

	//公共信息
	public function common($uid) {
		$UExt = D('Employee','Model', 'Admin');
		$userList = $UExt->getUserById($uid); //主表信息
		$extList = $UExt->getUserExtById($uid); //获取从表信息
		//处理一下工号
		$k = 6 - strlen($extList['ext_yggh']);
		for($j = 0 ; $j < $k ;$j ++ ){
			$extList['ext_yggh'] = '0'. $extList['ext_yggh'];
		}
		$contentList = array(
			'user' => $userList,
			'userExt' => $extList
		);
		return $contentList;
	}

	//根据id查询用户信息
	public function selectUExt($uid){
		$res = array('r'=>0,'m'=>'服务器忙，请稍候再试');
		$wheres = array();
		$wheres['user_id'] = array('eq',$uid);
		$uinfo = M('User')->where($wheres)->find();
		$einfo = M('user_extension')->where($wheres)->find();
		$userInfo = array('user'=>$uinfo,'userExt'=>$einfo);
		// $userInfo = array_merge($einfo,$uinfo);
		// dump($userInfo);
		if($userInfo){
			$res['r'] =1;
			$res['m'] = 'OK';
			$res['data'] = $userInfo;
		}else{
			$res['m'] = "客户不存在";
		}
		return $res;
	}
	//用户修改密码
	public function resetPass($_uid, $_pwd)
	{
		$r = array('r'=>0,'m'=>'服务器忙，请稍候再试 return');
		$wheres = array();
		$pdata = array();
		if( $_uid ){
			$wheres['user_id'] = array('eq' , $_uid);
			$uinfo = M('user')->field('login_name,create_time')->where($wheres)->find();
			if( $uinfo ){
				$pdata['pass'] = md6($_pwd.$uinfo['login_name'].$uinfo['create_time']);
				$pdata['last_time'] = date('Y-m-d H:i:s');
				$pdata['last_ip'] = get_client_ip();
				$ret = M('user')->where($wheres)->save($pdata);
				if($ret){
					$r['r'] = 1;
					$r['m'] = "密码重置成功";
				}else{
					$r['m'] = "很抱歉，密码重置失败";
				}
			}else{
				$r['m'] = "很抱歉，查找用户失败";
			}
		}
		return $r;
	}

	//添加新用户
	public function addUser( $addData,$extData )
	{
		$r = array('d'=>NULL,'i'=>'','r'=>0);
		$wheres = array();
		$d = array();
		if (!$addData || !$extData){
			$r['i'] = "提交参数错误";
			return $r;
		}
		/*if(!$addData['pwd']){
			$r['i'] = '密码不能为空';
			return $r;
		}*/
		if(!$extData['ext_name']) {
			$r['i'] = '姓名不能为空';
			return $r;
		}
		if(!$addData['phone']){
			$r['i'] = '手机号不能为空';
			return $r;
		}else{
			$phoneArr = M('user')->where("phone=".$addData['phone'])->select();
			if( $phoneArr ){
				$r['i'] = '手机号已存在';
				return $r;
			}
		}
		if(!$addData['weixin']){
			$r['i'] = '微信号不能为空';
			return $r;
		}else{
			$wxArr = M('user')->where("weixin=".$addData['weixin'])->select();
			if($wxArr){
				$r['i'] = '微信号已存在';
				return $r;
			}
		}
		if (!$addData['sector_id']) {
			$r['i'] = '部门信息不能为空';
			return $r;
		}
		// $uid = 0;
		if (isset($addData['phone']) && $addData['phone']) {
			$find = $this->_fieldCheck($uid, 'phone', $addData['phone']);
			if ($find)
				$r['i'] = "电话号码重复";
		}
		if (isset($addData['weixin']) && $addData['weixin']) {
			$find = $this->_fieldCheck($uid, 'weixin', $addData['weixin']);
			if ($find)
				$r['i'] = "微信号重复";
		}
		if ($r['i']) {
			return $r;
		}

		//昵称和姓名一致
		$addData['nickname'] = $extData['ext_name'];
		//默认密码
        $addData['pwd'] = 'hzhfzx';
        
		//生成用户登录名
		$MSector = M('Sector');
        $wheres = array();
        $wheres['sector_id'] = array('eq', $addData['sector_id']);
        $team = '';
        $dsector = $MSector->where( $wheres )->find();
        if ($dsector&&$dsector['is_subcompany']) {
        	$team = $dsector['sector_name'];
        }
       	else if ($dsector) {
       		$wheres['sector_id'] = array('eq', $dsector['parent_company']);
       		$team = $MSector->where( $wheres )->getField("sector_name");
       	}
       	if(!$team) {
       		$team = '系统';
       	}
        $wherel = array();
        $login_name =  ff_letter_first( msubstr($team,0,1)).ff_letter_first( msubstr($team,1,1));
        $wherel['login_name'] = array('like', $login_name.'%');
        $lastUser = M('user')->where( $wherel )->order("user_id desc")->find();
        if($lastUser){
            $ucnt = intval( substr($lastUser['login_name'],2) ) + 1;
        }
        else{
            $ucnt = 1;
        }

        $code = sprintf("%04d",$ucnt);
        $addData['login_name'] = $login_name.$code;
		$addData['create_time'] = date('Y-m-d H:i:s');
		$addData['last_time'] = $addData['create_time'];
		$addData['last_ip'] = get_client_ip();
		$addData['pass'] = md6($addData['pwd'].$addData['login_name'].$addData['create_time']);

		//生成工号
		$gh = M('user_extension')->max('ext_yggh');
		if($gh == '' || $gh == null){
			$gh = 0;
		}else{
			$gh = $gh + 1;
		}
		
		$extData['ext_yggh'] = $gh;
		$uId = M('user')->add( $addData );
		if($uId) {
			$extData['user_id'] = $uId;
			$ret = M('user_extension')->add($extData);
			if ($ret) {
				$reAll = array('user'=>$addData,'userExt'=>$extData);
				$r['r'] = 1;
				// $r['data'] = $login_name.$code;
				$r['data'] = $reAll;
				$r['i'] = '用户添加成功';
			} else {
				$r['i'] = '用户添加失败';
			}
		}
		return $r;
	}

 	private function _fieldCheck($uid, $field, $value)
 	{
 		$wherec = array();
		$wherec['user_id'] = array('neq', $uid );
		$wherec[$field] = array('eq', $value);
		if (!$value)
			return 0;
		$cnt = M('user')->where( $wherec)->count();
		return $cnt ? 1:0;
 	}

	public function saveDecInfo($uid,$userData,$emplData){
		$r = array('d'=>NULL,'i'=>'','r'=>0);
		$emplRes = '';
		$userRes = M('user')->where('user_id='.$uid)->save($userData);
		$res = M('user_extension')->where('user_id='.$uid)->find();
		if( $res ) {
			$emplRes = M('user_extension')->where('user_id='.$uid)->save($emplData);
		}else{
			$emplData['usser_id'] = $uid;
			$emplRes = M('user_extension')->add($emplData);
		}
		if(is_numeric($userRes) &&  is_numeric($emplRes)){
			$r['r'] = 1;
		}
		return $r;
	}

}
?>
